package org.i9.slb.platform.anseko.provider.repository;

import org.i9.slb.platform.anseko.provider.dto.InstanceDto;
import org.i9.slb.platform.anseko.provider.repository.mapper.InstanceRowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.UUID;

/**
 * 实例dao
 *
 * @author R12
 * @version 1.0
 * @date 2018/9/4 10:48
 */
@Repository
public class InstanceRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获取实例信息
     *
     * @param id
     * @return
     */
    public InstanceDto getInstanceDtoInfo(String id) {
        String sql = "SELECT id, instanceName, virtualType, remoteAddress, createDate FROM t_instance WHERE id = ?";
        List<InstanceDto> list = this.jdbcTemplate.query(sql, new Object[]{id}, new InstanceRowMapper());
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 获取实例列表
     *
     * @return
     */
    public List<InstanceDto> getInstanceDtoList() {
        String sql = "SELECT id, instanceName, virtualType, remoteAddress, createDate FROM t_instance ORDER BY createDate DESC";
        List<InstanceDto> list = this.jdbcTemplate.query(sql, new InstanceRowMapper());
        return list;
    }

    /**
     * 保存实例信息
     *
     * @param instanceDto
     */
    public void insertInstanceInfo(InstanceDto instanceDto) {
        String sql = "INSERT INTO t_instance (id, instanceName, virtualType, remoteAddress, createDate) VALUES (?, ?, ?, ?, NOW())";
        this.jdbcTemplate.update(sql,
                new Object[]{
                        UUID.randomUUID().toString(),
                        instanceDto.getInstanceName(),
                        instanceDto.getVirtualType(),
                        instanceDto.getRemoteAddress()
                });
    }
}
